<template>
  <div class="service-page bg-gray-50 dark:bg-gray-900 min-h-screen">
    <!-- 页面头部 -->
    <div class="page-header bg-white dark:bg-gray-800 shadow-sm">
      <!-- 面包屑导航 -->
      <div
        class="container mx-auto px-4 py-4 border-b border-gray-200 dark:border-gray-700"
      >
        <Breadcrumb
          :items="[{ path: '/', title: '首页' }, { title: '便民服务' }]"
        />
      </div>

      <div class="container mx-auto px-4 py-6">
        <div class="flex items-center justify-between">
          <div>
            <h1 class="text-2xl font-bold text-gray-900 dark:text-white">
              便民服务
            </h1>
            <p class="text-gray-600 dark:text-gray-400 mt-2">
              一站式便民服务，让您的旅途更加便捷
            </p>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区 -->
    <div class="container mx-auto px-4 py-8">
      <!-- 快速入口区 -->
      <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-8">
        <div
          class="service-card bg-white dark:bg-gray-800 rounded-lg shadow-md p-6 cursor-pointer hover:shadow-lg transition-shadow"
          @click="openAIChat"
        >
          <div class="flex items-center mb-4">
            <el-icon class="text-primary-500 dark:text-primary-400 text-2xl"
              ><ChatDotRound
            /></el-icon>
            <h3
              class="text-lg font-semibold ml-2 text-gray-900 dark:text-white"
            >
              智能客服
            </h3>
          </div>
          <p class="text-gray-600 dark:text-gray-400">
            24小时在线，智能解答您的问题
          </p>
        </div>

        <div
          class="service-card bg-white dark:bg-gray-800 rounded-lg shadow-md p-6 cursor-pointer hover:shadow-lg transition-shadow"
          @click="openHumanService"
        >
          <div class="flex items-center mb-4">
            <el-icon class="text-primary-500 dark:text-primary-400 text-2xl"
              ><Service
            /></el-icon>
            <h3
              class="text-lg font-semibold ml-2 text-gray-900 dark:text-white"
            >
              人工客服
            </h3>
          </div>
          <p class="text-gray-600 dark:text-gray-400">工作时间：9:00-18:00</p>
        </div>

        <div
          class="service-card bg-white dark:bg-gray-800 rounded-lg shadow-md p-6 cursor-pointer hover:shadow-lg transition-shadow"
          @click="openFeedback"
        >
          <div class="flex items-center mb-4">
            <el-icon class="text-primary-500 dark:text-primary-400 text-2xl"
              ><Edit
            /></el-icon>
            <h3
              class="text-lg font-semibold ml-2 text-gray-900 dark:text-white"
            >
              问题反馈
            </h3>
          </div>
          <p class="text-gray-600 dark:text-gray-400">提交您的问题和建议</p>
        </div>
      </div>

      <!-- FAQ区域 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow-md p-6 mb-8">
        <div class="flex items-center justify-between mb-6">
          <h2 class="text-xl font-semibold text-gray-900 dark:text-white">
            常见问题
          </h2>
          <el-input
            v-model="searchQuery"
            placeholder="搜索问题..."
            class="max-w-xs dark:bg-gray-700 dark:text-gray-300 dark:border-gray-600"
            :prefix-icon="Search"
            @input="handleSearch"
          />
        </div>

        <el-collapse
          v-model="activeNames"
          class="dark:border-gray-700 faq-collapse"
        >
          <el-collapse-item
            v-for="faq in filteredFAQs"
            :key="faq.id"
            :title="faq.question"
            :name="faq.id"
            class="dark:border-gray-700 faq-item"
          >
            <template #title>
              <span class="text-gray-900 dark:text-gray-200 font-medium">{{
                faq.question
              }}</span>
            </template>
            <div
              class="text-gray-600 dark:text-gray-400 py-3 px-1"
              v-html="faq.answer"
            ></div>
          </el-collapse-item>
        </el-collapse>

        <div class="text-center mt-6">
          <el-button
            type="primary"
            text
            class="dark:text-primary-400 hover:text-primary-500 dark:hover:text-primary-300"
            @click="showAllFAQs"
          >
            查看全部问题
          </el-button>
        </div>
      </div>

      <!-- 联系方式 -->
      <div class="bg-white dark:bg-gray-800 rounded-lg shadow-md p-6">
        <div class="flex items-center justify-between mb-6">
          <h2 class="text-xl font-semibold text-gray-900 dark:text-white">
            联系我们
          </h2>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-8">
          <!-- 左侧联系信息 -->
          <div class="space-y-6">
            <div
              class="service-time-card bg-primary-50 dark:bg-primary-900/20 rounded-lg p-4"
            >
              <h3
                class="text-lg font-medium text-primary-600 dark:text-primary-400 mb-3"
              >
                服务时间
              </h3>
              <div class="space-y-2 text-gray-600 dark:text-gray-400">
                <p>工作日：周一至周五 09:00-18:00</p>
                <p>周末/节假日：10:00-16:00</p>
                <p class="text-sm mt-2">* 智能客服 24 小时在线</p>
              </div>
            </div>

            <div
              class="urgent-contact-card bg-red-50 dark:bg-red-900/20 rounded-lg p-4"
            >
              <h3
                class="text-lg font-medium text-red-600 dark:text-red-400 mb-3"
              >
                紧急联系
              </h3>
              <div class="space-y-2">
                <p class="text-gray-600 dark:text-gray-400">
                  24小时紧急服务热线
                </p>
                <p class="text-lg font-semibold text-red-600 dark:text-red-400">
                  400-888-9999
                </p>
                <p class="text-sm text-gray-500 dark:text-gray-400 mt-2">
                  * 仅用于处理紧急情况
                </p>
              </div>
            </div>
          </div>

          <!-- 右侧联系方式 -->
          <div class="space-y-6">
            <div class="contact-channels space-y-4">
              <div
                class="channel-item flex items-start space-x-3 p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg"
              >
                <el-icon
                  class="text-2xl text-primary-500 dark:text-primary-400 mt-1"
                  ><Message
                /></el-icon>
                <div>
                  <h4 class="font-medium text-gray-900 dark:text-white">
                    商务合作
                  </h4>
                  <p class="text-gray-600 dark:text-gray-400 mt-1">
                    business@example.com
                  </p>
                  <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">
                    合作洽谈、品牌推广、市场活动
                  </p>
                </div>
              </div>

              <div
                class="channel-item flex items-start space-x-3 p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg"
              >
                <el-icon
                  class="text-2xl text-primary-500 dark:text-primary-400 mt-1"
                  ><Service
                /></el-icon>
                <div>
                  <h4 class="font-medium text-gray-900 dark:text-white">
                    客户服务
                  </h4>
                  <p class="text-gray-600 dark:text-gray-400 mt-1">
                    service@example.com
                  </p>
                  <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">
                    订单问题、退款售后、投诉建议
                  </p>
                </div>
              </div>

              <div
                class="channel-item flex items-start space-x-3 p-3 bg-gray-50 dark:bg-gray-700/50 rounded-lg"
              >
                <el-icon
                  class="text-2xl text-primary-500 dark:text-primary-400 mt-1"
                  ><Location
                /></el-icon>
                <div>
                  <h4 class="font-medium text-gray-900 dark:text-white">
                    来访地址
                  </h4>
                  <p class="text-gray-600 dark:text-gray-400 mt-1">
                    贵港市港北区贵港大道123号文化旅游大厦15楼
                  </p>
                  <p class="text-sm text-gray-500 dark:text-gray-400 mt-1">
                    工作日接待参观、交流
                  </p>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 社交媒体 -->
        <div class="mt-8 pt-6 border-t border-gray-200 dark:border-gray-700">
          <h3 class="text-lg font-medium text-gray-900 dark:text-white mb-4">
            关注我们
          </h3>
          <div class="flex items-center space-x-6">
            <div class="social-item text-center cursor-pointer group">
              <div
                class="w-12 h-12 flex items-center justify-center bg-gray-100 dark:bg-gray-800 rounded-full group-hover:bg-primary-50 dark:group-hover:bg-primary-900/20 transition-colors"
              >
                <img
                  src="/images/social/wechat.png"
                  alt="微信"
                  class="w-6 h-6"
                />
              </div>
              <span class="block mt-2 text-sm text-gray-600 dark:text-gray-400"
                >微信</span
              >
            </div>
            <div class="social-item text-center cursor-pointer group">
              <div
                class="w-12 h-12 flex items-center justify-center bg-gray-100 dark:bg-gray-800 rounded-full group-hover:bg-primary-50 dark:group-hover:bg-primary-900/20 transition-colors"
              >
                <img
                  src="/images/social/weibo.png"
                  alt="微博"
                  class="w-6 h-6"
                />
              </div>
              <span class="block mt-2 text-sm text-gray-600 dark:text-gray-400"
                >微博</span
              >
            </div>
            <div class="social-item text-center cursor-pointer group">
              <div
                class="w-12 h-12 flex items-center justify-center bg-gray-100 dark:bg-gray-800 rounded-full group-hover:bg-primary-50 dark:group-hover:bg-primary-900/20 transition-colors"
              >
                <img
                  src="/images/social/douyin.png"
                  alt="抖音"
                  class="w-6 h-6"
                />
              </div>
              <span class="block mt-2 text-sm text-gray-600 dark:text-gray-400"
                >抖音</span
              >
            </div>
            <div class="social-item text-center cursor-pointer group">
              <div
                class="w-12 h-12 flex items-center justify-center bg-gray-100 dark:bg-gray-800 rounded-full group-hover:bg-primary-50 dark:group-hover:bg-primary-900/20 transition-colors"
              >
                <img
                  src="/images/social/xiaohongshu.png"
                  alt="小红书"
                  class="w-6 h-6"
                />
              </div>
              <span class="block mt-2 text-sm text-gray-600 dark:text-gray-400"
                >小红书</span
              >
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- AI客服对话框 -->
    <el-dialog
      v-model="showAIChat"
      title="智能客服"
      width="80%"
      class="ai-chat-dialog dark:bg-gray-800"
      :before-close="handleCloseAIChat"
      :show-close="false"
    >
      <template #header>
        <div class="flex justify-between items-center px-4 py-3">
          <h3 class="text-xl font-medium dark:text-white">智能客服</h3>
          <el-button type="text" @click="showAIChat = false" class="dialog-header-button">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
      </template>
      <div class="chat-container dark:bg-gray-800" style="height: 600px">
        <div class="chat-messages dark:bg-gray-900" ref="aiMessagesContainer">
          <div
            v-for="message in chatMessages"
            :key="message.time"
            :class="[
              'message-item flex',
              message.type === 'user' ? 'justify-end' : 'justify-start',
            ]"
          >
            <template v-if="message.type === 'ai'">
              <el-avatar :size="36" :src="message.avatar" class="mt-2" />
              <div class="message-content max-w-[70%] ml-2">
                <div
                  class="bg-gray-100 dark:bg-gray-700 rounded-lg p-3 dark:text-gray-300"
                >
                  {{ message.content }}
                </div>
                <div class="text-xs text-gray-500 dark:text-gray-400 mt-1">
                  {{ message.time }}
                </div>
              </div>
            </template>
            <template v-else>
              <div class="message-content max-w-[70%]">
                <div class="flex items-end justify-end">
                  <div
                    class="bg-primary-500 text-white dark:bg-primary-600 rounded-lg p-3"
                  >
                    {{ message.content }}
                  </div>
                </div>
                <div
                  class="text-xs text-gray-500 dark:text-gray-400 mt-1 text-right"
                >
                  {{ message.time }}
                </div>
              </div>
            </template>
          </div>
          <div v-if="isAITyping" class="message-item flex justify-start">
            <el-avatar
              :size="36"
              src="/images/avatars/ai-avatar.png"
              class="mt-2"
            />
            <div class="message-content max-w-[70%] ml-2">
              <div class="bg-gray-100 dark:bg-gray-700 rounded-lg p-3">
                <div class="typing-indicator dark:bg-gray-700">
                  <span class="dark:bg-gray-400"></span>
                  <span class="dark:bg-gray-400"></span>
                  <span class="dark:bg-gray-400"></span>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="chat-input-area dark:bg-gray-800 dark:border-gray-700">
          <div class="flex space-x-2">
            <el-input
              v-model="chatInput"
              placeholder="请输入您的问题..."
              class="dark:bg-gray-700 dark:text-gray-300 dark:border-gray-600"
              @keyup.enter="sendMessage"
            />
            <el-button
              type="primary"
              @click="sendMessage"
              class="dark:bg-primary-600 dark:hover:bg-primary-700"
              >发送</el-button
            >
          </div>
          <div class="quick-questions mt-4">
            <el-tag
              v-for="question in quickQuestions"
              :key="question"
              class="mr-2 mb-2 cursor-pointer dark:bg-gray-700 dark:text-gray-300 dark:border-gray-600 hover:bg-gray-200 dark:hover:bg-gray-600"
              @click="quickAsk(question)"
            >
              {{ question }}
            </el-tag>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 人工客服对话框 -->
    <el-dialog
      v-model="showHumanService"
      :title="getServiceDialogTitle"
      width="80%"
      :close-on-click-modal="false"
      :before-close="handleCloseHumanService"
      class="human-service-dialog dark:bg-gray-800"
      :show-close="false"
    >
      <template #header>
        <div class="flex justify-between items-center px-4 py-3">
          <h3 class="text-xl font-medium dark:text-white">{{ getServiceDialogTitle }}</h3>
          <el-button type="text" @click="showHumanService = false" class="dialog-header-button">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
      </template>
      <!-- 等待连接状态 -->
      <div
        v-if="humanServiceData.status === 'waiting'"
        class="waiting-container dark:bg-gray-800"
      >
        <el-icon class="text-6xl text-primary-500 dark:text-primary-400 mb-4"
          ><Service
        /></el-icon>
        <h3 class="text-xl font-medium mb-4 dark:text-white">
          正在为您接入人工客服
        </h3>
        <p class="text-gray-600 dark:text-gray-400 mb-4">
          当前等待人数：{{ waitingNumber }} 人
        </p>
        <el-progress :percentage="connectionProgress" />
        <div class="mt-8">
          <p class="text-gray-500 dark:text-gray-400">温馨提示：</p>
          <p class="text-gray-500 dark:text-gray-400">
            1. 当前为工作时间,预计等待时间3-5分钟
          </p>
          <p class="text-gray-500 dark:text-gray-400">
            2. 您也可以选择智能客服或留言
          </p>
          <p class="text-gray-500 dark:text-gray-400">
            3. 排队过程中请勿刷新或关闭页面
          </p>
        </div>
      </div>

      <!-- 聊天界面 -->
      <div
        v-else-if="humanServiceData.status === 'connected'"
        class="chat-container dark:bg-gray-800"
        style="height: 600px; overflow: hidden"
      >
        <!-- 客服信息 -->
        <div class="agent-info border-b p-4">
          <div class="flex items-center justify-between">
            <div class="flex items-center">
              <el-avatar
                :size="40"
                :src="humanServiceData.currentAgent.avatar"
              />
              <div class="ml-3">
                <div class="agent-name font-medium">
                  {{ humanServiceData.currentAgent.name }}
                  <el-tag size="small" class="agent-status ml-2">{{
                    getAgentStatus
                  }}</el-tag>
                </div>
                <div class="agent-rating text-sm">
                  <el-rate
                    v-model="humanServiceData.currentAgent.rating"
                    disabled
                    :max="5"
                  />
                  <span class="ml-2"
                    >已服务 {{ humanServiceData.currentAgent.serviceCount }}+
                    人次</span
                  >
                </div>
              </div>
            </div>
            <div class="flex items-center space-x-2">
              <el-tooltip content="转接其他客服" placement="top">
                <el-button
                  type="primary"
                  plain
                  size="small"
                  :loading="humanServiceData.isTransferring"
                  @click="transferToOtherAgent"
                >
                  <el-icon><SwitchButton /></el-icon>
                  转接客服
                </el-button>
              </el-tooltip>
              <el-tooltip content="结束对话" placement="top">
                <el-button
                  type="danger"
                  plain
                  size="small"
                  @click="endHumanService"
                >
                  <el-icon><CircleClose /></el-icon>
                  结束对话
                </el-button>
              </el-tooltip>
            </div>
          </div>
          <div class="agent-skills mt-2">
            <el-tag
              v-for="skill in humanServiceData.currentAgent.skills"
              :key="skill"
              size="small"
              class="mr-1"
            >
              {{ skill }}
            </el-tag>
          </div>
        </div>

        <!-- 消息区域 -->
        <div class="chat-messages" ref="messagesContainer">
          <!-- 会话开始提示 -->
          <div class="text-center text-gray-500 text-sm mb-4">
            <span
              >会话开始时间:
              {{ formatDateTime(humanServiceData.sessionStartTime) }}</span
            >
          </div>

          <div
            v-for="(message, index) in humanServiceData.messages"
            :key="index"
          >
            <!-- 系统消息 -->
            <div
              v-if="message.type === 'system'"
              class="message-item flex justify-center"
            >
              <div class="message-system px-4 py-2 rounded-full text-sm">
                {{ message.content }}
                <span class="text-xs ml-2">{{ message.time }}</span>
              </div>
            </div>

            <!-- 用户消息 -->
            <div
              v-else-if="message.type === 'user'"
              class="message-item flex justify-end"
            >
              <div class="message-content user-message max-w-[70%]">
                <div class="flex items-end justify-end">
                  <div class="message-status text-xs text-gray-400 mr-1">
                    <el-icon
                      v-if="message.status === 'sending'"
                      class="animate-spin"
                      ><Loading
                    /></el-icon>
                    <el-icon
                      v-else-if="message.status === 'sent'"
                      class="text-gray-400"
                      ><Check
                    /></el-icon>
                    <el-icon
                      v-else-if="message.status === 'error'"
                      class="text-red-500"
                      ><Warning
                    /></el-icon>
                  </div>
                  <div class="rounded-lg p-3">
                    <div v-if="message.contentType === 'text'">
                      {{ message.content }}
                    </div>
                    <div v-else-if="message.contentType === 'image'">
                      <el-image
                        :src="message.content"
                        :preview-src-list="[message.content]"
                        class="max-w-[200px] rounded cursor-pointer"
                        fit="cover"
                      />
                    </div>
                    <div
                      v-else-if="message.contentType === 'file'"
                      class="flex items-center"
                    >
                      <el-icon class="mr-2"><Document /></el-icon>
                      <div class="flex-1 overflow-hidden">
                        <div class="truncate">{{ message.fileName }}</div>
                        <div class="text-xs">
                          {{ formatFileSize(message.fileSize) }}
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <div class="message-time text-xs mt-1 text-right">
                  {{ message.time }}
                </div>
              </div>
            </div>

            <!-- 客服消息 -->
            <div
              v-else-if="message.type === 'agent'"
              class="message-item flex justify-start"
            >
              <el-avatar :size="36" :src="message.agent.avatar" class="mt-2" />
              <div class="message-content agent-message max-w-[70%] ml-2">
                <div class="rounded-lg p-3">
                  <div v-if="message.contentType === 'text'">
                    {{ message.content }}
                  </div>
                  <div v-else-if="message.contentType === 'image'">
                    <el-image
                      :src="message.content"
                      :preview-src-list="[message.content]"
                      class="max-w-[200px] rounded cursor-pointer"
                      fit="cover"
                    />
                  </div>
                  <div
                    v-else-if="message.contentType === 'file'"
                    class="flex items-center"
                  >
                    <el-icon class="mr-2"><Document /></el-icon>
                    <div class="flex-1 overflow-hidden">
                      <div class="truncate">{{ message.fileName }}</div>
                      <div class="text-xs">
                        {{ formatFileSize(message.fileSize) }}
                      </div>
                    </div>
                  </div>
                </div>
                <div class="message-time text-xs mt-1">{{ message.time }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="chat-input-area border-t">
          <!-- 工具栏 -->
          <div class="toolbar border-b px-4 py-2 flex items-center space-x-3">
            <div class="relative">
              <el-tooltip content="发送表情" placement="top">
                <div
                  class="tool-button"
                  :class="{ active: humanServiceData.showEmojiPanel }"
                  @click.stop="
                    humanServiceData.showEmojiPanel =
                      !humanServiceData.showEmojiPanel
                  "
                >
                  <el-icon><Sunny /></el-icon>
                </div>
              </el-tooltip>

              <!-- 表情面板 -->
              <div
                v-if="humanServiceData.showEmojiPanel"
                class="emoji-panel absolute bottom-full left-0 mb-2 z-50"
                @click.stop
              >
                <div
                  class="grid grid-cols-8 gap-1 p-4 bg-white dark:bg-gray-800 border dark:border-gray-700 rounded-lg shadow-lg"
                >
                  <div
                    v-for="emoji in emojiList"
                    :key="emoji"
                    class="emoji-item cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700 p-2 text-center rounded text-xl transition-colors duration-200"
                    @click="insertEmoji(emoji)"
                  >
                    {{ emoji }}
                  </div>
                </div>
              </div>
            </div>
            <el-tooltip content="发送图片" placement="top">
              <el-upload
                class="upload-inline"
                action="/api/upload"
                :show-file-list="false"
                :before-upload="beforeImageUpload"
                :on-success="handleImageSuccess"
                :on-error="handleImageError"
              >
                <div class="tool-button">
                  <el-icon><Picture /></el-icon>
                </div>
              </el-upload>
            </el-tooltip>
            <el-tooltip content="发送文件" placement="top">
              <el-upload
                class="upload-inline"
                action="/api/upload"
                :show-file-list="false"
                :before-upload="beforeFileUpload"
                :on-success="handleFileSuccess"
                :on-error="handleFileError"
              >
                <div class="tool-button">
                  <el-icon><Upload /></el-icon>
                </div>
              </el-upload>
            </el-tooltip>
            <div class="h-5 w-px bg-gray-200 dark:bg-gray-700 mx-1"></div>
            <el-tooltip content="截图" placement="top">
              <div class="tool-button" @click="startScreenshot">
                <el-icon><Crop /></el-icon>
              </div>
            </el-tooltip>
          </div>

          <!-- 常用语 -->
          <div class="common-phrases px-4 py-2">
            <el-tabs
              v-model="activePhraseType"
              class="demo-tabs"
              @tab-click="handleClick"
            >
              <el-tab-pane
                v-for="type in commonPhrases"
                :key="type.type"
                :label="getPhraseTypeLabel(type.type)"
                :name="type.type"
              >
                <div class="flex flex-wrap gap-2">
                  <el-tag
                    v-for="phrase in type.phrases"
                    :key="phrase"
                    class="cursor-pointer"
                    @click="insertPhrase(phrase)"
                  >
                    {{ phrase }}
                  </el-tag>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>

          <!-- 输入框 -->
          <div class="input-area px-4 py-2">
            <div class="flex space-x-2">
              <el-input
                v-model="humanServiceData.input"
                type="textarea"
                :rows="3"
                placeholder="请输入消息..."
                resize="none"
                @keyup.enter.exact="sendHumanMessage"
                @keyup.enter.shift.exact="humanServiceData.input += '\n'"
                @input="handleTyping"
              />
              <div class="flex flex-col justify-end">
                <el-button
                  type="primary"
                  :disabled="
                    !humanServiceData.input.trim() &&
                    !humanServiceData.selectedFile
                  "
                  @click="sendHumanMessage"
                >
                  发送
                </el-button>
              </div>
            </div>
            <div class="text-xs text-gray-500 mt-1">
              按 Enter 发送消息,Shift + Enter 换行
            </div>
          </div>
        </div>
      </div>

      <!-- 会话结束状态 -->
      <div v-else class="end-container">
        <el-result
          icon="success"
          title="会话已结束"
          sub-title="感谢您的使用,如有需要可以重新咨询"
        >
          <template #extra>
            <el-button type="primary" @click="showHumanService = false"
              >关闭</el-button
            >
          </template>
        </el-result>
      </div>
    </el-dialog>

    <!-- 问题反馈对话框 -->
    <el-dialog
      v-model="showFeedback"
      title="问题反馈"
      width="60%"
      :before-close="handleCloseFeedback"
      class="dark:bg-gray-800"
      :show-close="false"
    >
      <template #header>
        <div class="flex justify-between items-center px-4 py-3">
          <h3 class="text-xl font-medium dark:text-white">问题反馈</h3>
          <el-button type="text" @click="showFeedback = false" class="dialog-header-button">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
      </template>
      <el-form
        ref="feedbackForm"
        :model="feedbackForm"
        :rules="feedbackRules"
        label-width="100px"
        class="dark:text-gray-300"
      >
        <el-form-item label="问题类型" prop="type" class="dark:text-gray-300">
          <el-select
            v-model="feedbackForm.type"
            placeholder="请选择问题类型"
            class="dark:bg-gray-700"
          >
            <el-option
              v-for="item in feedbackTypes"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              class="dark:bg-gray-700 dark:text-gray-300"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="问题描述"
          prop="content"
          class="dark:text-gray-300"
        >
          <el-input
            v-model="feedbackForm.content"
            type="textarea"
            :rows="4"
            placeholder="请详细描述您遇到的问题..."
            class="dark:bg-gray-700 dark:text-gray-300"
          />
        </el-form-item>
        <el-form-item
          label="联系方式"
          prop="contact"
          class="dark:text-gray-300"
        >
          <el-input
            v-model="feedbackForm.contact"
            placeholder="请留下您的联系方式，方便我们回复您"
            class="dark:bg-gray-700 dark:text-gray-300"
          />
        </el-form-item>
        <el-form-item label="图片附件" class="dark:text-gray-300">
          <el-upload
            class="upload-demo dark:text-gray-300"
            action="/api/upload"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            multiple
            :limit="3"
            :on-exceed="handleExceed"
          >
            <el-button type="primary" class="dark:bg-gray-700"
              >点击上传</el-button
            >
            <template #tip>
              <div class="el-upload__tip dark:text-gray-400">
                只能上传 jpg/png 文件，且不超过 2MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button
            @click="showFeedback = false"
            class="dark:bg-gray-700 dark:text-gray-300"
            >取消</el-button
          >
          <el-button type="primary" @click="submitFeedback">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount, nextTick } from "vue";
import {
  ChatDotRound,
  Service,
  Edit,
  Search,
  Phone,
  Message,
  Location,
  Clock,
  Picture,
  Upload,
  Crop,
  Sunny,
  Close,
} from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";

// FAQ数据
const faqData = [
  {
    id: 1,
    question: "如何修改订单信息？",
    answer:
      '您可以在"我的订单"中找到需要修改的订单，点击"修改订单"按钮进行修改。请注意，订单支付后将无法修改订单信息。',
  },
  {
    id: 2,
    question: "支持哪些支付方式？",
    answer:
      "我们支持以下支付方式：<br>1. 支付宝<br>2. 微信支付<br>3. 银行卡支付<br>4. 余额支付",
  },
  {
    id: 3,
    question: "如何申请退款？",
    answer:
      '您可以在"我的订单"中找到需要退款的订单，点击"申请退款"按钮，填写退款原因后提交申请。我们会在2个工作日内处理您的退款申请。',
  },
  // 更多FAQ...
];

// 搜索相关
const searchQuery = ref("");
const activeNames = ref(["1"]);

// 根据搜索词过滤FAQ
const filteredFAQs = computed(() => {
  if (!searchQuery.value) return faqData;
  const query = searchQuery.value.toLowerCase();
  return faqData.filter(
    (faq) =>
      faq.question.toLowerCase().includes(query) ||
      faq.answer.toLowerCase().includes(query),
  );
});

// AI客服相关
const showAIChat = ref(false);
const chatInput = ref("");
const isAITyping = ref(false);
const chatMessages = ref([
  {
    type: "ai",
    content: "您好！我是智能客服小智，很高兴为您服务。请问有什么可以帮您？",
    time: new Date().toLocaleTimeString(),
    avatar: "/images/avatars/ai-avatar.png",
  },
]);

// 智能推荐问题
const quickQuestions = [
  "如何修改订单信息？",
  "退款政策是怎样的？",
  "景点门票可以提前多久预订？",
  "如何查看订单状态？",
  "如何评价和打分？",
  "忘记密码怎么办？",
  "如何修改手机号？",
  "如何查看我的积分？",
];

// 智能回复模板
const aiResponseTemplates = {
  ticket: {
    info: "请问您想了解哪个景点的具体信息？我可以为您提供：\n1. 景点开放时间\n2. 门票价格\n3. 交通路线\n4. 景点特色\n5. 周边配套设施",
    booking:
      "请提供以下信息，我来帮您预订：\n1. 参观日期\n2. 游客人数\n3. 是否需要导游\n4. 有无特殊需求",
    refund:
      "关于退票，请告诉我：\n1. 订单号\n2. 退票原因\n3. 购买时间\n我会帮您处理退票事宜。",
  },
  order: {
    modify: "请提供您的订单号和需要修改的内容，我来协助您处理。",
    status: "请提供您的订单号，我来查询具体状态。",
    payment:
      "请说明您遇到的具体支付问题，例如：\n- 支付失败\n- 重复扣款\n- 优惠券使用\n等，我会针对性地为您解决。",
  },
  complaint: {
    service:
      "请详细描述您遇到的问题：\n1. 发生时间\n2. 具体情况\n3. 您的诉求\n我们会认真处理您的投诉。",
    facility:
      "请说明：\n1. 问题设施位置\n2. 具体问题\n3. 发现时间\n我们会及时跟进处理。",
  },
};

// 智能匹配关键词
const keywordMap = {
  订单: "order",
  修改: "modify",
  状态: "status",
  退款: "refund",
  密码: "password",
  手机: "phone",
  积分: "points",
  门票: "ticket",
  预订: "booking",
  退订: "cancel",
};

// 发送消息
const sendMessage = async () => {
  if (!chatInput.value.trim()) return;

  // 添加用户消息
  const userMessage = {
    type: "user",
    content: chatInput.value,
    time: new Date().toLocaleTimeString(),
  };
  chatMessages.value.push(userMessage);

  // 清空输入框
  const userQuestion = chatInput.value;
  chatInput.value = "";

  // 显示AI正在输入状态
  isAITyping.value = true;

  try {
    await new Promise((resolve) => setTimeout(resolve, 1000));

    // 分析问题关键词
    const keywords = Object.keys(keywordMap);
    const matchedCategory = keywords.find((keyword) =>
      userQuestion.includes(keyword),
    );

    let aiResponse = "";
    if (matchedCategory) {
      const category = keywordMap[matchedCategory];
      const subCategories = Object.keys(aiResponseTemplates[category] || {});
      const matchedSubCategory = subCategories.find(
        (sub) =>
          userQuestion.includes(sub) ||
          userQuestion.includes(aiResponseTemplates[category][sub]),
      );

      if (matchedSubCategory) {
        aiResponse = aiResponseTemplates[category][matchedSubCategory];
      }
    }

    if (!aiResponse) {
      aiResponse =
        "抱歉，我可能没有完全理解您的问题。您可以：\n1. 换个方式描述问题\n2. 点击下方快捷问题\n3. 联系人工客服";

      const relatedQuestions = quickQuestions.filter((q) =>
        q.toLowerCase().includes(userQuestion.toLowerCase()),
      );

      if (relatedQuestions.length > 0) {
        aiResponse += "\n\n您可能想问：\n" + relatedQuestions.join("\n");
      }
    }

    // 添加AI回复，包含头像
    chatMessages.value.push({
      type: "ai",
      content: aiResponse,
      time: new Date().toLocaleTimeString(),
      avatar: "/images/avatars/ai-avatar.png",
    });
  } catch (error) {
    chatMessages.value.push({
      type: "ai",
      content: "抱歉，系统出现了一些问题，请稍后再试或联系人工客服。",
      time: new Date().toLocaleTimeString(),
      avatar: "/images/avatars/ai-avatar.png",
    });
  } finally {
    isAITyping.value = false;
  }
};

// 快速提问
const quickAsk = (question) => {
  chatInput.value = question;
  sendMessage();
};

// 人工客服相关
const showHumanService = ref(false);
const waitingNumber = ref(3);
const connectionProgress = ref(0);
const messagesContainer = ref(null);
const humanServiceStatus = ref("waiting"); // waiting, connected, ended
const humanChatMessages = ref([]);
const humanChatInput = ref("");
const currentAgent = ref(null);
const isTransferring = ref(false);

// 模拟客服数据
const serviceAgents = [
  {
    id: 1,
    name: "王小美",
    avatar: "/images/avatars/agent1.jpg",
    rating: 4.9,
    serviceCount: 2000,
    skills: ["订单处理", "退款售后"],
  },
  {
    id: 2,
    name: "李明",
    avatar: "/images/avatars/agent2.jpg",
    rating: 4.8,
    serviceCount: 1500,
    skills: ["产品咨询", "投诉处理"],
  },
  {
    id: 3,
    name: "张华",
    avatar: "/images/avatars/agent3.jpg",
    rating: 4.7,
    serviceCount: 1800,
    skills: ["技术支持", "账号问题"],
  },
];

// 修改commonPhrases为用户使用的快捷语
const commonPhrases = [
  {
    type: "inquiry",
    phrases: [
      "我想咨询景点门票价格",
      "请问景区开放时间是怎样的？",
      "我想了解景区的交通路线",
      "附近有什么推荐的住宿吗？",
    ],
  },
  {
    type: "order",
    phrases: [
      "我要修改订单信息",
      "我想取消订单",
      "订单支付遇到问题",
      "如何申请退款",
    ],
  },
  {
    type: "account",
    phrases: [
      "忘记密码怎么办",
      "如何修改手机号",
      "怎么查看我的积分",
      "会员等级有什么权益",
    ],
  },
  {
    type: "complaint",
    phrases: [
      "我要投诉服务态度",
      "景区设施有损坏",
      "预订流程不够清晰",
      "建议增加更多优惠活动",
    ],
  },
];

// 添加表情符号数据
const emojiList = [
  // 表情表达
  "😀",
  "😃",
  "😄",
  "😁",
  "😅",
  "😂",
  "🤣",
  "😊",
  "😇",
  "🙂",
  "🙃",
  "😉",
  "😌",
  "😍",
  "🥰",
  "😘",
  "😗",
  "😙",
  "😚",
  "😋",
  "😛",
  "😝",
  "😜",
  "🤪",
  "🤨",
  "🧐",
  "🤓",
  "😎",
  "🥸",
  "🤩",
  "🥳",
  "😏",
  "😒",
  "😞",
  "😔",
  "😟",
  "😕",
  "🙁",
  "☹️",
  "😣",
  "😖",
  "😫",
  "😩",
  "🥺",
  "😢",
  "😭",
  "😤",
  "😠",
  "😡",
  "🤬",
  "🤯",
  "😳",
  "🥵",
  "🥶",
  "😱",
  "😨",
  "😰",
  "😥",
  "😓",
  "🫣",

  // 手势和身体
  "👋",
  "🤚",
  "✋",
  "🖐️",
  "👌",
  "🤌",
  "🤏",
  "✌️",
  "🤞",
  "🫰",
  "🤟",
  "🤘",
  "🤙",
  "👈",
  "👉",
  "👆",
  "👇",
  "👍",
  "👎",
  "✊",
  "👊",
  "🤛",
  "🤜",
  "🫷",
  "🫸",
  "👏",
  "🙌",
  "👐",
  "🤲",
  "🫶",
  "🤝",
  "🙏",
  "💪",
  "🦾",
  "🫂",
  "🧠",
  "🫀",
  "🫁",
  "🦷",
  "🦴",

  // 动物
  "🐱",
  "🐶",
  "🐭",
  "🐹",
  "🐰",
  "🦊",
  "🐻",
  "🐼",
  "🐨",
  "🐯",
  "🦁",
  "🐮",
  "🐷",
  "🐸",
  "🐵",
  "🐔",
  "🐧",
  "🐦",
  "🦆",
  "🦅",

  // 自然和天气
  "🌸",
  "💮",
  "🌹",
  "🌺",
  "🌻",
  "🌼",
  "🌷",
  "🌱",
  "🌲",
  "🌳",
  "🌴",
  "🍀",
  "🍁",
  "🍂",
  "🍃",
  "⭐",
  "🌟",
  "✨",
  "⚡",
  "☀️",
  "🌤️",
  "⛅",
  "🌥️",
  "☁️",
  "🌦️",
  "🌧️",
  "⛈️",
  "🌩️",
  "🌨️",
  "❄️",
  "☃️",
  "⛄",
  "🌬️",
  "💨",
  "🌪️",
  "🌫️",
  "🌊",
  "💧",
  "💦",
  "☔",

  // 食物和饮料
  "🍎",
  "🍐",
  "🍊",
  "🍋",
  "🍌",
  "🍉",
  "🍇",
  "🍓",
  "🫐",
  "🍈",
  "🍒",
  "🍑",
  "🥭",
  "🍍",
  "🥥",
  "🥝",
  "🍅",
  "🥑",
  "🥦",
  "🥬",
  "🍔",
  "🍟",
  "🍕",
  "🌭",
  "🥪",
  "🌮",
  "🌯",
  "🫔",
  "🥙",
  "🧆",
  "🥚",
  "🍳",
  "🥘",
  "🍲",
  "🥣",
  "🥗",
  "🍿",
  "🧈",
  "🧂",
  "🥫",
  "☕",
  "🫖",
  "🍵",
  "🧃",
  "🥤",
  "🧋",
  "🍶",
  "🍺",
  "🍻",
  "🥂",
  "🍷",
  "🥃",
  "🍸",
  "🍹",
  "🧉",
  "🍾",
  "🧊",
  "🥄",
  "🍴",
  "🍽️",

  // 爱心和装饰
  "❤️",
  "🧡",
  "💛",
  "💚",
  "💙",
  "💜",
  "🤎",
  "🖤",
  "🤍",
  "💔",
  "❣️",
  "💕",
  "💞",
  "💓",
  "💗",
  "💖",
  "💘",
  "💝",
  "💟",
  "♥️",
  "🎈",
  "🎆",
  "🎇",
  "🎉",
  "🎊",
  "🎋",
  "🎍",
  "🎎",
  "🎏",
  "🎐",
  "🎑",
  "🎀",
  "🎁",
  "🎗️",
  "🎟️",
  "🎫",
  "🎖️",
  "🏆",
  "🏅",
  "��",
];

// 修改人工客服相关变量
const humanServiceData = ref({
  status: "waiting", // waiting, connected, ended
  messages: [],
  input: "",
  currentAgent: null,
  isTransferring: false,
  showEmojiPanel: false,
  selectedFile: null,
  uploadProgress: 0,
  isTyping: false,
  lastTypingTime: 0,
  typingTimeout: null,
  unreadCount: 0,
  sessionStartTime: null,
  quickReplies: [
    "我想咨询景点相关信息",
    "我需要帮助修改订单",
    "我想了解退款政策",
    "我遇到了支付问题",
    "我需要投诉服务",
    "我想查询订单状态",
  ],
});

// 添加计算属性
const getServiceDialogTitle = computed(() => {
  if (humanServiceData.value.status === "waiting") {
    return "人工客服 - 等待接入";
  } else if (humanServiceData.value.status === "connected") {
    return `人工客服 - ${humanServiceData.value.currentAgent?.name || ""}`;
  } else {
    return "人工客服";
  }
});

const getAgentStatus = computed(() => {
  if (humanServiceData.value.isTransferring) {
    return "转接中";
  } else if (humanServiceData.value.isTyping) {
    return "正在输入";
  } else {
    return "在线";
  }
});

// 添加工具方法
const formatDateTime = (date) => {
  if (!date) return "";
  return new Date(date).toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
};

const formatFileSize = (bytes) => {
  if (!bytes) return "0 B";
  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return `${(bytes / Math.pow(k, i)).toFixed(1)} ${sizes[i]}`;
};

const scrollToBottom = () => {
  const container = messagesContainer.value;
  if (container) {
    container.scrollTop = container.scrollHeight;
    humanServiceData.value.unreadCount = 0;
  }
};

const checkScroll = () => {
  const container = messagesContainer.value;
  if (container) {
    const isAtBottom =
      container.scrollHeight - container.scrollTop - container.clientHeight <
      100;
    if (!isAtBottom) {
      humanServiceData.value.unreadCount++;
    }
  }
};

// 打开人工客服
const openHumanService = async () => {
  showHumanService.value = true;
  humanServiceData.value = {
    status: "waiting",
    messages: [],
    input: "",
    currentAgent: null,
    isTransferring: false,
    showEmojiPanel: false,
    selectedFile: null,
    uploadProgress: 0,
    isTyping: false,
    lastTypingTime: 0,
    typingTimeout: null,
    unreadCount: 0,
    sessionStartTime: new Date(),
    quickReplies: [
      "我想咨询景点相关信息",
      "我需要帮助修改订单",
      "我想了解退款政策",
      "我遇到了支付问题",
      "我需要投诉服务",
      "我想查询订单状态",
    ],
  };
  connectionProgress.value = 0;
  waitingNumber.value = Math.floor(Math.random() * 5) + 1; // 1-5人随机等待

  // 模拟排队进度
  const timer = setInterval(() => {
    if (connectionProgress.value < 100) {
      connectionProgress.value += 10;
      // 模拟前面等待人数减少
      if (waitingNumber.value > 0 && connectionProgress.value % 30 === 0) {
        waitingNumber.value--;
      }
    } else {
      clearInterval(timer);
      connectToAgent();
    }
  }, 1000);
};

// 连接到客服
const connectToAgent = () => {
  humanServiceData.value.status = "connected";
  // 随机分配客服
  const agent = serviceAgents[Math.floor(Math.random() * serviceAgents.length)];
  humanServiceData.value.currentAgent = agent;

  // 添加系统消息
  addMessage({
    type: "system",
    content: `已接入客服${agent.name}，请描述您需要帮助的问题`,
    time: new Date().toLocaleTimeString(),
  });

  // 添加客服欢迎消息
  addMessage({
    type: "agent",
    agent: agent,
    contentType: "text",
    content: `您好，我是${agent.name}。请问有什么可以帮您？您可以：\n1. 咨询景点信息\n2. 订单相关问题\n3. 退款事宜\n4. 投诉建议`,
    time: new Date().toLocaleTimeString(),
  });
};

// 添加消息
const addMessage = (message) => {
  humanServiceData.value.messages.push(message);
  // 检查滚动位置
  nextTick(() => {
    checkScroll();
  });
};

// 发送消息
const sendHumanMessage = async () => {
  if (
    !humanServiceData.value.input.trim() &&
    !humanServiceData.value.selectedFile
  )
    return;

  let message;
  if (humanServiceData.value.selectedFile) {
    // 发送文件消息
    message = {
      type: "user",
      contentType: humanServiceData.value.selectedFile.type.startsWith("image/")
        ? "image"
        : "file",
      content: URL.createObjectURL(humanServiceData.value.selectedFile),
      fileName: humanServiceData.value.selectedFile.name,
      fileSize: humanServiceData.value.selectedFile.size,
      status: "sending",
      time: new Date().toLocaleTimeString(),
    };
  } else {
    // 发送文本消息
    message = {
      type: "user",
      contentType: "text",
      content: humanServiceData.value.input.trim(),
      status: "sending",
      time: new Date().toLocaleTimeString(),
    };
  }

  // 添加消息
  addMessage(message);

  // 清空输入
  humanServiceData.value.input = "";
  humanServiceData.value.selectedFile = null;

  try {
    // 模拟发送延迟
    await new Promise((resolve) => setTimeout(resolve, 500));

    // 更新消息状态
    message.status = "sent";

    // 等待客服回复提示
    addMessage({
      type: "system",
      content: "消息已发送，请耐心等待客服回复",
      time: new Date().toLocaleTimeString(),
    });
  } catch (error) {
    message.status = "error";
    ElMessage.error("消息发送失败，请重试");
  }
};

// 插入表情
const insertEmoji = (emoji) => {
  humanServiceData.value.input += emoji;
  humanServiceData.value.showEmojiPanel = false;
};

// 插入常用语
const insertPhrase = (phrase) => {
  humanServiceData.value.input = phrase;
};

// 文件上传相关方法
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error("只能上传图片文件！");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过 2MB！");
    return false;
  }

  humanServiceData.value.selectedFile = file;
  return false; // 阻止自动上传
};

const beforeFileUpload = (file) => {
  const isLt10M = file.size / 1024 / 1024 < 10;

  if (!isLt10M) {
    ElMessage.error("文件大小不能超过 10MB！");
    return false;
  }

  humanServiceData.value.selectedFile = file;
  return false; // 阻止自动上传
};

const handleImageSuccess = (response, file) => {
  // 处理图片上传成功
};

const handleImageError = () => {
  ElMessage.error("图片上传失败，请重试");
};

const handleFileSuccess = (response, file) => {
  // 处理文件上传成功
};

const handleFileError = () => {
  ElMessage.error("文件上传失败，请重试");
};

// 截图功能
const startScreenshot = () => {
  ElMessage.info("截图功能开发中...");
};

// 下载文件
const downloadFile = (message) => {
  // 实现文件下载逻辑
  const link = document.createElement("a");
  link.href = message.content;
  link.download = message.fileName;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};

// 监听滚动
onMounted(() => {
  const container = messagesContainer.value;
  if (container) {
    container.addEventListener("scroll", () => {
      const isAtBottom =
        container.scrollHeight - container.scrollTop - container.clientHeight <
        100;
      if (isAtBottom) {
        humanServiceData.value.unreadCount = 0;
      }
    });
  }
});

// 清理工作
onBeforeUnmount(() => {
  if (humanServiceData.value.typingTimeout) {
    clearTimeout(humanServiceData.value.typingTimeout);
  }
});

// 方法定义
const handleSearch = () => {
  // 实现搜索逻辑
};

const showAllFAQs = () => {
  // 跳转到完整的FAQ页面
};

const openAIChat = () => {
  showAIChat.value = true;
};

const handleCloseAIChat = (done) => {
  // 直接关闭对话框
  showAIChat.value = false;
};

const handleCloseHumanService = (done) => {
  // 直接关闭对话框
  showHumanService.value = false;
};

const handleCloseFeedback = (done) => {
  // 直接关闭对话框
  showFeedback.value = false;
};

// 在script setup中添加getPhraseTypeLabel函数
const getPhraseTypeLabel = (type) => {
  const labelMap = {
    inquiry: "景点咨询",
    order: "订单相关",
    account: "账户问题",
    complaint: "投诉建议",
  };
  return labelMap[type] || type;
};

// 添加activePhraseType的ref
const activePhraseType = ref("inquiry");

// 添加handleClick函数
const handleClick = (tab) => {
  activePhraseType.value = tab.props.name;
};

// 添加问题反馈相关变量
const showFeedback = ref(false);
const feedbackForm = ref({
  type: "",
  content: "",
  contact: "",
  images: [],
});

// 添加反馈类型选项
const feedbackTypes = [
  { value: "service", label: "服务问题" },
  { value: "facility", label: "设施问题" },
  { value: "product", label: "产品建议" },
  { value: "other", label: "其他问题" },
];

// 添加表单验证规则
const feedbackRules = {
  type: [{ required: true, message: "请选择问题类型", trigger: "change" }],
  content: [{ required: true, message: "请描述您的问题", trigger: "blur" }],
  contact: [{ required: true, message: "请留下您的联系方式", trigger: "blur" }],
};

// 添加打开反馈对话框的方法
const openFeedback = () => {
  showFeedback.value = true;
};

// 添加提交反馈的方法
const submitFeedback = () => {
  const feedbackFormRef = ref(null);
  feedbackFormRef.value.validate((valid) => {
    if (valid) {
      // 这里添加提交反馈的逻辑
      ElMessage.success("反馈提交成功，我们会尽快处理！");
      showFeedback.value = false;
    } else {
      return false;
    }
  });
};

// 添加点击其他地方关闭表情面板的处理
onMounted(() => {
  document.addEventListener("click", () => {
    humanServiceData.value.showEmojiPanel = false;
  });
});

onBeforeUnmount(() => {
  document.removeEventListener("click", () => {
    humanServiceData.value.showEmojiPanel = false;
  });
});
</script>

<style lang="scss" scoped>
.service-page {
  .service-card {
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2px);
    }
  }

  .contact-item {
    text-align: center;
  }

  .ai-chat-dialog,
  .human-service-dialog {
    :deep(.el-dialog__body) {
      padding: 0;
      height: 600px;
      overflow: hidden;
    }
  }

  .chat-container {
    height: 100%;
    display: flex;
    flex-direction: column;
    background-color: #fff;
  }

  .chat-messages {
    flex: 1;
    height: 0;
    min-height: 0;
    overflow-y: auto;
    padding: 20px;
    background-color: #f5f7fa;

    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background-color: #ddd;
      border-radius: 3px;
    }

    &.dark {
      background-color: #1a1a1a;

      &::-webkit-scrollbar-thumb {
        background-color: #4a4a4a;
      }
    }
  }

  .chat-input-area {
    flex: none;
    background-color: #fff;
    border-top: 1px solid #eee;
    padding: 10px;

    &.dark {
      background-color: #1a1a1a;
      border-color: #2d2d2d;
    }
  }

  .agent-info {
    flex: none;
    background-color: #f8f9fa;
    border-bottom: 1px solid #eee;
    padding: 10px;

    &.dark {
      background-color: #1a1a1a;
      border-color: #2d2d2d;
    }
  }

  .message-item {
    margin-bottom: 16px;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .message-content {
    max-width: 70%;
  }

  .emoji-panel {
    position: absolute;
    bottom: 100%;
    left: 0;
    z-index: 10;
  }

  .new-message-alert {
    position: fixed;
    bottom: 120px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 10;
  }

  .quick-questions {
    margin-top: 10px;

    .el-tag {
      margin-right: 8px;
      margin-bottom: 8px;
      cursor: pointer;

      &:hover {
        opacity: 0.8;
      }

      &.dark {
        background-color: #2d2d2d;
        border-color: #4a4a4a;
        color: #e0e0e0;
      }
    }
  }

  .toolbar {
    padding: 8px;
    border-bottom: 1px solid #eee;

    &.dark {
      border-color: #2d2d2d;
    }
  }

  .common-phrases {
    padding: 8px;
  }

  .input-area {
    padding: 8px;
  }

  .waiting-container,
  .end-container {
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    padding: 20px;
  }

  .faq-collapse {
    :deep(.el-collapse-item__header) {
      background-color: transparent;
      border-bottom: 1px solid #e5e7eb;
      padding: 16px 8px;
      font-size: 16px;

      &:hover {
        background-color: #f9fafb;
      }

      .dark & {
        border-bottom: 1px solid #374151;

        &:hover {
          background-color: #1f2937;
        }
      }
    }

    :deep(.el-collapse-item__content) {
      background-color: transparent;
      padding: 16px 8px;

      .dark & {
        background-color: #111827;
      }
    }

    :deep(.el-collapse-item__arrow) {
      color: #6b7280;

      .dark & {
        color: #9ca3af;
      }
    }

    :deep(.el-collapse-item.is-active) {
      .el-collapse-item__header {
        font-weight: 600;

        .dark & {
          color: #e5e7eb;
        }
      }
    }
  }

  .faq-item {
    border-radius: 8px;
    overflow: hidden;
    margin-bottom: 8px;
    transition: all 0.3s ease;

    &:last-child {
      margin-bottom: 0;
    }

    .dark & {
      background-color: #1f2937;
      border: 1px solid #374151;

      &:hover {
        border-color: #4b5563;
      }
    }
  }

  .dialog-header-button {
    @apply text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200;
  }
}

.typing-indicator {
  display: flex;
  gap: 4px;

  span {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background-color: #666;
    animation: typing 1s infinite ease-in-out;

    &:nth-child(1) {
      animation-delay: 0.2s;
    }
    &:nth-child(2) {
      animation-delay: 0.3s;
    }
    &:nth-child(3) {
      animation-delay: 0.4s;
    }

    &.dark {
      background-color: #999;
    }
  }
}

@keyframes typing {
  0%,
  100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-4px);
  }
}

.feedback-form {
  .el-form-item__content {
    .el-select,
    .el-input {
      width: 100%;
    }
  }

  .feedback-upload {
    :deep(.el-upload--picture-card) {
      width: 100px;
      height: 100px;
      line-height: 100px;
    }

    &.dark {
      :deep(.el-upload--picture-card) {
        background-color: #2d2d2d;
        border-color: #4a4a4a;
      }
    }
  }
}

.ai-chat-dialog {
  :deep(.el-dialog) {
    background-color: #fff;

    .dark & {
      background-color: #1f2937;
      border: 1px solid #374151;
    }
  }

  :deep(.el-dialog__header) {
    border-bottom: 1px solid #e5e7eb;

    .dark & {
      border-color: #374151;

      .el-dialog__title {
        color: #e5e7eb;
      }

      .el-dialog__close {
        color: #9ca3af;

        &:hover {
          color: #e5e7eb;
        }
      }
    }
  }

  :deep(.el-dialog__body) {
    padding: 0;
    height: 600px;
    overflow: hidden;

    .dark & {
      background-color: #1f2937;
    }
  }
}

.chat-messages {
  flex: 1;
  height: 0;
  min-height: 0;
  overflow-y: auto;
  padding: 20px;
  background-color: #f5f7fa;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-thumb {
    background-color: #ddd;
    border-radius: 3px;
  }

  .dark & {
    background-color: #111827;

    &::-webkit-scrollbar-thumb {
      background-color: #4b5563;
    }
  }
}

.chat-input-area {
  flex: none;
  background-color: #fff;
  border-top: 1px solid #e5e7eb;
  padding: 16px;

  .dark & {
    background-color: #1f2937;
    border-color: #374151;
  }

  .el-input {
    .dark & {
      :deep(.el-input__wrapper) {
        background-color: #374151;
        border-color: #4b5563;
        box-shadow: none;

        &.is-focus {
          border-color: #60a5fa;
        }

        input {
          color: #e5e7eb;

          &::placeholder {
            color: #9ca3af;
          }
        }
      }
    }
  }

  .el-button {
    .dark & {
      &.el-button--primary {
        background-color: #3b82f6;
        border-color: #3b82f6;

        &:hover {
          background-color: #2563eb;
          border-color: #2563eb;
        }
      }
    }
  }
}

.quick-questions {
  .el-tag {
    transition: all 0.3s ease;

    .dark & {
      background-color: #374151;
      border-color: #4b5563;
      color: #e5e7eb;

      &:hover {
        background-color: #4b5563;
        border-color: #6b7280;
      }
    }
  }
}

.typing-indicator {
  display: flex;
  gap: 4px;

  span {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background-color: #6b7280;
    animation: typing 1s infinite ease-in-out;

    &:nth-child(1) {
      animation-delay: 0.2s;
    }
    &:nth-child(2) {
      animation-delay: 0.3s;
    }
    &:nth-child(3) {
      animation-delay: 0.4s;
    }

    .dark & {
      background-color: #9ca3af;
    }
  }
}

.human-service-dialog {
  :deep(.el-dialog) {
    background-color: #fff;

    .dark & {
      background-color: #1f2937;
      border: 1px solid #374151;
    }
  }

  :deep(.el-dialog__header) {
    border-bottom: 1px solid #e5e7eb;

    .dark & {
      border-color: #374151;
      background-color: #1f2937;

      .el-dialog__title {
        color: #e5e7eb;
      }

      .el-dialog__close {
        color: #9ca3af;

        &:hover {
          color: #e5e7eb;
        }
      }
    }
  }

  :deep(.el-dialog__body) {
    padding: 0;
    height: 600px;
    overflow: hidden;

    .dark & {
      background-color: #1f2937;
    }
  }

  .agent-info {
    background-color: #f8f9fa;
    border-bottom: 1px solid #e5e7eb;

    .dark & {
      background-color: #1f2937;
      border-color: #374151;

      .agent-name {
        color: #e5e7eb;
      }

      .agent-status {
        background-color: #374151;
        color: #9ca3af;
      }

      .agent-rating {
        color: #9ca3af;
      }

      .agent-skills {
        .el-tag {
          background-color: #374151;
          border-color: #4b5563;
          color: #9ca3af;
        }
      }
    }
  }

  .message-content {
    .dark & {
      &.user-message {
        background-color: #3b82f6;
        color: #fff;
      }

      &.agent-message {
        background-color: #374151;
        color: #e5e7eb;
      }

      .message-time {
        color: #9ca3af;
      }
    }
  }

  .quick-replies {
    .dark & {
      .el-tag {
        background-color: #374151;
        border-color: #4b5563;
        color: #e5e7eb;

        &:hover {
          background-color: #4b5563;
          border-color: #6b7280;
        }
      }
    }
  }
}

.chat-messages {
  .message-item {
    .dark & {
      .message-system {
        background-color: #374151;
        color: #9ca3af;
      }

      .message-content {
        &.user-message {
          background-color: #3b82f6;
          color: #fff;
        }

        &.agent-message {
          background-color: #374151;
          color: #e5e7eb;
        }

        .message-time {
          color: #9ca3af;
        }
      }
    }
  }
}

.toolbar {
  position: relative; // 确保相对定位

  .tool-button {
    @apply w-8 h-8 flex items-center justify-center rounded-lg cursor-pointer transition-all duration-200;
    @apply text-gray-500 hover:text-primary-500 hover:bg-primary-50;

    .dark & {
      @apply text-gray-400 hover:text-primary-400 hover:bg-primary-900/20;
    }

    &.active {
      @apply text-primary-500 bg-primary-50;

      .dark & {
        @apply text-primary-400 bg-primary-900/20;
      }
    }

    .el-icon {
      @apply text-xl;
    }
  }

  .upload-inline {
    @apply inline-block;
  }

  .emoji-panel {
    width: 360px; // 调整宽度
    max-height: 400px; // 增加高度
    overflow-y: auto;
    box-shadow:
      0 4px 12px -2px rgba(0, 0, 0, 0.12),
      0 4px 8px -2px rgba(0, 0, 0, 0.08);

    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-thumb {
      background-color: #ddd;
      border-radius: 3px;

      .dark & {
        background-color: #4b5563;
      }
    }

    &::-webkit-scrollbar-track {
      background-color: transparent;
    }

    .emoji-item {
      &:hover {
        transform: scale(1.1);
        transition: transform 0.2s ease;
      }
    }
  }
}
</style>
